package com.bonc.web.xss;

import com.bonc.util.exception.BusinessException;
import com.bonc.util.response.CommResponseEnum;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 用于过滤包含文件参数的HttpServletRequest
 * @author wangxiaoyun
 */
public class XssMultipartHttpServletRequestWrapper extends DefaultMultipartHttpServletRequest {

    public XssMultipartHttpServletRequestWrapper(HttpServletRequest request, MultiValueMap<String, MultipartFile> mpFiles, Map<String, String[]> mpParams, Map<String, String> mpParamContentTypes) {
        super(request);
        this.setMultipartFiles(mpFiles);
        this.setMultipartParameters(mpParams);
        this.setMultipartParameterContentTypes(mpParamContentTypes);
    }

    @Override
    public String getHeader(String name) {
        return StringEscapeUtils.escapeHtml4(super.getHeader(name));
    }

    @Override
    public String getQueryString() {
        return SequenceTool.xssEncode(super.getQueryString()).toString();
    }

    @Override
    public String getParameter(String name) {
        return StringEscapeUtils.escapeHtml4(super.getParameter(name));
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> multipartParameters = this.getMultipartParameters();
        if (multipartParameters.isEmpty()) {
            return super.getParameterMap();
        } else {
            //过滤map中的参数值
            SensitivewordFilter filter = new SensitivewordFilter();
            for (Map.Entry<String, String[]> entry : multipartParameters.entrySet()) {
                if (entry.getValue() != null && entry.getValue().length > 0) {

                    String[] ss = new String[1];
                    //判断是否包含敏感字符
                    if(filter.getSensitiveWord(entry.getValue()[0],1).size()>0){
                        throw new BusinessException(CommResponseEnum.APIERROR6);
                    }
                    // 替换危险字符，并存入原始map
                    ss[0] = SequenceTool.xssEncode(entry.getValue()[0]).toString();
                    multipartParameters.put(entry.getKey(), ss);
                }
            }
            return multipartParameters;
        }
    }
}
